package com.jy.app.lib.net;

import android.content.Intent;

import com.alibaba.fastjson.TypeReference;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.jy.app.lib.application.BaseApplication;
import com.jy.app.lib.base.Constants;
import com.jy.app.lib.bean.BaseResponse;
import com.jy.app.lib.utils.JsonUtil;
import com.jy.app.lib.utils.LogUtil;
import com.jy.app.lib.utils.ToastUtils;

import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;

import cz.msebera.android.httpclient.Header;


/**
 * 通用数据返回接口，自己处理数据
 * Created by jan on 2016/5/5.
 */
public class CommonHttpResponseHandler extends AsyncHttpResponseHandler {

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        if (responseBody != null) {
            String content = null;
            try {
                content = new String(responseBody, "UTF-8");
                final BaseResponse<String> br = JsonUtil.parseObject(content, new TypeReference<BaseResponse<String>>() {
                });
                BaseResponse res = ((BaseResponse) br);
                if (res != null) {
                    if (res instanceof BaseResponse) {
                        BaseResponse<String> response = ((BaseResponse) res);
                        if (response.getCode() != 0) {
                            if (response.getCode() == 500) {
                                ToastUtils.toastShort(BaseApplication.appContext, "账号登录已失效，请重新登录");
                                BaseApplication.appContext.startActivity(new Intent(BaseApplication.appContext, Class.forName(BaseApplication.loginActivity))
                                        .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                                | Intent.FLAG_ACTIVITY_CLEAR_TASK).putExtra(Constants.KEY_NEED_CLEANPWD, true));
                            } else {
                                onFailure(response.getCode(), response.getMsg());
                            }
                        }
                    }
                }
                if (HttpUtil.ENABLE_LOG) {
                    LogUtil.i("[HttpUtils]->response=" + content);
                }
                onSuccess(content);
            } catch (ClassCastException cle){
                cle.printStackTrace();
                onSuccess(content);
            }catch (Exception e) {
                onFailure(10000, "onSuccess has error:" + e.getLocalizedMessage());
                e.printStackTrace();
            }
        } else {
            onFailure(10000, "responseBody is null");
        }
    }

    /**
     * 请求成功后的回调，返回一个string
     *
     * @param responseString
     */
    protected void onSuccess(String responseString) {
    }

    /**
     * 带失败码和错误信息的回调
     *
     * @param statusCode
     * @param warnStr
     */

    protected void onFailure(int statusCode, String warnStr) {
    }

    /**
     * 返回一个精确到后2位的百分比
     *
     * @param progress
     */
    protected void onProgress(String progress) {
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        if (responseBody != null) {
            try {
                String content = new String(responseBody, "UTF-8");
                onFailure(statusCode, content);
            } catch (UnsupportedEncodingException e) {
                onFailure(10000, "onFailure has error:" + e.getLocalizedMessage());
                e.printStackTrace();
            }
        } else {
            onFailure(10000, error.getLocalizedMessage());
        }
    }

    @Override
    public void onProgress(long bytesWritten, long totalSize) {
        super.onProgress(bytesWritten, totalSize);
        if (bytesWritten > 0 && totalSize > 0) {
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String progress = numberFormat.format((float) bytesWritten / (float) totalSize * 100);
            onProgress(progress);
        }
    }
}
